import turtle

# 4.绘制谢尔宾斯地毯

def siepinski(degree,point):
    colormap=["white","black"]
    draw(point,colormap[1 if degree>1 else 0])
    if degree>1:
        points = tirmidps(point)
        for i,j in [(0,0),(0,1),(0,2),
                    (1,0),      (1,2),
                    (2,0),(2,1),(2,2)]:
            siepinski(degree-1,{
                'left_top': points[i][j],
                'right_top': points[i][j+1],
                'left_bottom': points[i+1][j],
                'right_bottom': points[i+1][j+1],
                })

def draw(points,color):
    t.fillcolor(color)
    t.penup()
    t.goto(points['left_top'])
    t.pendown()
    t.begin_fill()
    t.goto(points['right_top'])
    t.goto(points['right_bottom'])
    t.goto(points['left_bottom'])
    t.goto(points['left_top'])
    t.end_fill()


def tirmidps(ps):
    result = [[list() for _ in range(4)]for _ in range(4)]
    for i in range(4):
        for j in range(4):
            for dim in range(2):
                result[i][j].append(
                    ((3-i)*(3-j)*ps["left_top"][dim]+
                     (3-i)*j*ps["right_top"][dim]+
                     i*(3-j)*ps["left_bottom"][dim]+
                    i*j*ps["right_bottom"][dim])/9)
    return result


points = {
    'left_top': (-400,400),
    'right_top': (400,400),
    'left_bottom': (-400,-400),
    'right_bottom': (400,-400),
}

turtle.setup(width=1000,height=1000)
t = turtle.Turtle()
turtle.tracer(False)
t.pencolor("white")
siepinski(6,points)
t.penup()
# turtle.done()

# 图像保存
turtle.getscreen().getcanvas().postscript(file="siepinski.eps")
